//
//  HYYPhotoScrollerV.m
//  CTalk
//
//  Created by panluyao on 16/10/25.
//  Copyright © 2016年 Chinac.com. All rights reserved.
//

#import "HYYPhotoScrollerV.h"

@interface HYYPhotoScrollerV ()<UIScrollViewDelegate>
{
    UIImageView *imageV;
}

@end

@implementation HYYPhotoScrollerV

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (id)initWithFrame:(CGRect)frame image:(UIImage *)img
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        
        imageV = [[UIImageView alloc] initWithImage:img];
        CGFloat imageScale = CGRectGetWidth(frame) / CGRectGetWidth(imageV.bounds);
        
        self.delegate = self;
        
        CGFloat minScale = MIN(1.0, imageScale);
        
        CGFloat maxScale = 2.0;
//        if ([UIScreen instancesRespondToSelector:@selector(scale)]) {
//            maxScale = maxScale / [[UIScreen mainScreen] scale];
//        }
        
        self.maximumZoomScale = maxScale;
        self.minimumZoomScale = minScale;
        
        CGFloat imgHeight = CGRectGetHeight(imageV.bounds) * imageScale;
        CGFloat imgY = MAX(0, (CGRectGetHeight(frame) - imgHeight)/2);
        CGRect imageFrame = CGRectMake(0, imgY, CGRectGetWidth(frame),  imgHeight);
        self.contentSize = CGSizeMake(CGRectGetWidth(imageFrame), CGRectGetHeight(imageFrame));
        imageV.frame = imageFrame;
        [self addSubview:imageV];
        self.decelerationRate = UIScrollViewDecelerationRateFast;
    }
    return self;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?
    (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
    CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?
    (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
    // setCenter!!!!!!!!
    imageV.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,
                                scrollView.contentSize.height * 0.5 + offsetY);
}

//告诉scrollview要缩放的是哪个子控件
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return imageV;
}

@end
